package com.lzw.breezeNovel.webApp.message;

import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author 清风明月
 * @Package com.lzw.breezeNovel.webApp.message
 * @date 2025/3/27
 * @description 自定义心跳处理器
 */
@Slf4j
@Component
@SuppressWarnings("all")
public class HeartBeatHandler extends ChannelDuplexHandler {

    /**
     * 读取数据
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent) evt;
            if(event.state() == IdleState.READER_IDLE){
                Channel channel = ctx.channel();
                //获取用户的标识
                Attribute<String> attr = channel.attr(AttributeKey.valueOf(channel.id().toString()));
                String phone = attr.get();
                log.info("用户" + phone + "超时");
                ctx.close();
            }else if(event.state() == IdleState.WRITER_IDLE){
                log.info("写超时");
                ctx.close();
            }
        }
    }

}
